package ee.ttu.karileet.serviceshop.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import ee.ttu.karileet.serviceshop.bo.CustomerBO;
import ee.ttu.karileet.serviceshop.model.Person;
import ee.ttu.karileet.serviceshop.model.ServiceRequest;
import ee.ttu.karileet.serviceshop.model.ServiceRequestStatusType;
import ee.ttu.karileet.serviceshop.service.CustomerService;
import ee.ttu.karileet.serviceshop.service.EmployeeService;
import ee.ttu.karileet.serviceshop.service.PersonService;
import ee.ttu.karileet.serviceshop.service.ServiceRequestService;
import ee.ttu.karileet.serviceshop.service.ServiceRequestStatusTypeService;
import ee.ttu.karileet.serviceshop.service.UserAccountService;

@Controller
@RequestMapping("/json.htm")
public class AjaxController {
	
	@Autowired
	private ServiceRequestService serviceRequestService;
	@Autowired
	private ServiceRequestStatusTypeService serviceRequestStatusTypeService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private PersonService personService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model){
		CustomerBO c = null;
		Person p = null;
		ServiceRequestStatusType serviceRequestStatusType = null;
		//command object
		List<ServiceRequest> requests = serviceRequestService.getServiceRequests();
		StringBuffer sb = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		sb.append("{\"aaData\":[");
		for(ServiceRequest sr : requests) {
			c = customerService.getCustomerById(sr.getCustomerFk());
			p = personService.getPersonById(sr.getCreatedBy());
			serviceRequestStatusType = serviceRequestStatusTypeService.getServiceRequestStatusTypeById(sr.getServiceRequestStatusTypeFk());
			if (sb2.length() > 0) {
				sb2.append(",");
			}
			sb2.append("[\"")
			.append(c.getSubject().getFirstName()).append(" ").append(c.getSubject().getLastName()).append("\",\"")
			.append(p.getFirstName()).append(" ").append(p.getLastName()).append("\",\"")
			.append(sr.getCreated()).append("\",\"")
			.append(sr.getServiceDescByCustomer()).append("\",\"")
			.append(sr.getServiceDescByEmployee()).append("\",\"")
			.append(serviceRequestStatusType.getTypeName())
			.append("\"]");
		}
		sb.append(sb2);
		sb.append("]}");
		model.addAttribute("json", sb.toString());
 
		//return form view
		return "plainText";
	}
}
